package logger

import (
	"fmt"
	"os"
	"path"
	"strings"
	"time"
)

// FileLogger 日志输出文件结构体
type FileLogger struct {
	filePath string   //文件目录
	fileName string   //文件名称
	logLevel LogLevel //日志界别
}

// NewFileLog 初始化文件日志
func NewFileLog(filePath string, logLevel LogLevel) *FileLogger {
	return &FileLogger{
		filePath: filePath,
		logLevel: logLevel,
	}
}

func (f *FileLogger) writelog(logLevel string, format string, a ...interface{}) {
	if !f.enable(logLevel) {
		return
	}
	fileName := fmt.Sprintf("%s.log", time.Now().Format("2006-01-02"))
	filePath := path.Join(f.filePath, fileName)
	file, err := os.OpenFile(filePath, os.O_CREATE|os.O_APPEND, 0644)
	if err != nil {
		fmt.Printf("打开%s文件出错！%v\n", filePath, err)
		return
	}
	defer file.Close()
	formatStr := fmt.Sprintf(format, a...)
	msg := fmt.Sprintf("[%s] %s %s\n", time.Now().Format("2006-01-02 15:04:05"), logLevel, formatStr)
	file.WriteString(msg)
}

// Trace 级别日志跟踪
func (f *FileLogger) Trace(format string, a ...interface{}) {
	f.writelog("TRACE", format, a...)
}

// Debug 级别日志跟踪
func (f *FileLogger) Debug(format string, a ...interface{}) {
	f.writelog("DEBUG", format, a...)
}

// Warning 级别日志跟踪
func (f *FileLogger) Warning(format string, a ...interface{}) {
	f.writelog("WARNING", format, a...)
}

// Info 级别日志跟踪
func (f *FileLogger) Info(format string, a ...interface{}) {
	f.writelog("INFO", format, a...)
}

// Error 级别日志跟踪
func (f *FileLogger) Error(format string, a ...interface{}) {
	f.writelog("ERROR", format, a...)
}

// 是否开启当前级别的日志
func (f *FileLogger) enable(logLevel string) bool {
	switch strings.ToUpper(logLevel) {
	case "TRACE":
		return LevelTrace >= f.logLevel
	case "DEBUG":
		return LevelDebug >= f.logLevel
	case "INFO":
		return LevelInfo >= f.logLevel
	case "WARNING":
		return LevelWarning >= f.logLevel
	case "ERROR":
		return LevelError >= f.logLevel
	default:
		return LevelInfo >= f.logLevel
	}
}
